<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="68px">
      <el-row>
        <el-card shadow="always" style="margin-bottom: 10px;">
          <el-radio-group v-model="queryType" size="mini">
            <el-radio border key="2" :v-show="rightType <= 1" label="2">分公司</el-radio>
            <el-radio border key="3" :v-show="rightType <= 2" label="3">分区</el-radio>
            <el-radio border key="4" :v-show="rightType <= 3" label="4">部门归属</el-radio>
            <el-radio border key="6" :v-show="rightType <= 4" label="6">个人</el-radio>
          </el-radio-group>
        </el-card>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="时间" prop="goalDate">
            <el-date-picker v-model="queryParams.goalDate" type="week" format="yyyy 第 WW 周" value-format="yyyy-MM-dd"
              placeholder="选择周">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="部门归属" prop="orgId" v-if="queryType == 6">
            <treeselect v-model="queryParams.orgId" :options="deptOptions" :show-count="true" placeholder="请选择部门归属"
              :default-expand-level="4" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="顾问" prop="empId" v-if="queryType == 6">
            <el-select v-model="queryParams.empId" placeholder="顾问" clearable filterable>
              <el-option v-for="user in sysUsersList" :key="user.userId" :label="user.nickName" :value="user.userId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain v-if="rightType == 4" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['crmsys:userGoal:add']">新增目标</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userGoalList" @selection-change="handleSelectionChange" show-summary :summary-method="getSummaries">
      <el-table-column label="顾问" align="center" prop="nick_name" v-if="queryType == 6" />
      <el-table-column label="部门归属" align="center" prop="dept_name" />
      <el-table-column label="上门目标" align="center" prop="visit" />
      <el-table-column label="实际上门" align="center" prop="visit_real" />
      <el-table-column label="签约目标" align="center" prop="signed" />
      <el-table-column label="实际签约" align="center" prop="signed_real" />
      <el-table-column label="新增好友目标" align="center" prop="add_friend" />
      <el-table-column label="实际新增好友" align="center" prop="add_friend_real" />
      <el-table-column label="小贷客户数目标" align="center" prop="introduce" />
      <el-table-column label="实际小贷客户数" align="center" prop="introduce_real" />
      <el-table-column label="短信目标" align="center" prop="smsfollow" />
      <el-table-column label="实际短信" align="center" prop="smsfollow_real" />
      <el-table-column label="通时目标" align="center" prop="call_time" />
      <el-table-column label="实际通时" align="center" prop="call_time_real" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" prop="operation">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit"
            v-if="userId == scope.row.emp_id && checkGoalDate(scope.row.goalDate)" @click="handleUpdate(scope.row)"
            v-hasPermi="['crmsys:userGoal:edit']">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改周目标管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">

        <el-form-item label="目标日期" prop="goalDate">
          <el-date-picker v-model="form.goalDate" type="week" format="yyyy 第 WW 周" value-format="yyyy-MM-dd"
            placeholder="选择目标日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="上门目标" prop="visit">
          <el-input v-model.number="form.visit" placeholder="请输入上门目标" />
        </el-form-item>
        <el-form-item label="签约目标" prop="signed">
          <el-input v-model.number="form.signed" placeholder="请输入签约目标" />
        </el-form-item>
        <el-form-item label="新增好友目标" prop="addFriend">
          <el-input v-model.number="form.addFriend" placeholder="请输入新增好友目标" />
        </el-form-item>
        <el-form-item label="小贷客户数目标" prop="introduce">
          <el-input v-model.number="form.introduce" placeholder="请输入小贷客户数目标" />
        </el-form-item>
        <el-form-item label="小贷担保客户目标" prop="introduceVisit">
          <el-input v-model.number="form.introduceVisit" placeholder="请输入小贷担保客户目标" />
        </el-form-item>
        <el-form-item label="扫码签约目标" prop="introduceSigned">
          <el-input v-model.number="form.introduceSigned" placeholder="请输入扫码签约目标" />
        </el-form-item>
        <el-form-item label="短信目标" prop="smsfollow">
          <el-input v-model.number="form.smsfollow" placeholder="请输入短信目标" />
        </el-form-item>
        <el-form-item label="通时目标" prop="callTime">
          <el-input v-model.number="form.callTime" placeholder="请输入通时目标" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUserGoal, getUserGoal, delUserGoal, addUserGoal, updateUserGoal } from "@/api/crmsys/report/userGoal";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Treeselect from "@riophae/vue-treeselect";
import { childrenAlldeptTree } from "@/api/system/user";
import {
  getAllDeptandUsers
} from "@/api/crmsys/custinfo/custinfo";

export default {
  name: "UserGoal",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      queryType: "6",
      rightType: 4,
      // 总条数
      total: 0,
      // 周目标管理表格数据
      userGoalList: [],
      // 部门归属树选项
      deptOptions: [],
      sysUsersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultValue: null,
      userId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        empId: null,
        orgId: null,
        visit: null,
        signed: null,
        addFriend: null,
        introduce: null,
        introduceVisit: null,
        introduceSigned: null,
        smsfollow: null,
        callTime: null,
        goalDate: null,
        params: {
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        visit: [
          { required: true, message: "上门目标不能为空", trigger: "blur" },
          {pattern: /^[0-9]*$/,message: "上门目标必须是数字", trigger: "blur"}
        ],
        signed: [
          { required: true, message: "签约目标不能为空", trigger: "blur" },
          {pattern: /^[0-9]*$/,message: "签约目标必须是数字", trigger: "blur"}
        ],
        addFriend: [
          { required: true, message: "新增好友目标不能为空", trigger: "blur" },
          {pattern: /^[0-9]*$/,message: "新增好友目标必须是数字", trigger: "blur"}
        ],
        goalDate: [
          { required: true, message: "请选择目标日期", trigger: "blur" }
        ],
        introduce: [
          { required: true, message: "小贷客户数目标不能为空", trigger: "blur" },
          {pattern: /^[0-9]*$/,message: "小贷客户数目标必须是数字", trigger: "blur"}
        ],
        introduceVisit: [
          { required: true, message: "小贷担保客户目标不能为空", trigger: "blur" },
          {pattern: /^[0-9]*$/,message: "小贷担保客户目标必须是数字", trigger: "blur"}
        ],
        introduceSigned: [
          { required: true, message: "扫码签约目标不能为空", trigger: "blur" },
          {pattern: /^[0-9]*$/,message: "扫码签约目标必须是数字", trigger: "blur"}
        ],
        smsfollow: [
          { required: true, message: "短信目标不能为空", trigger: "blur" },
          {pattern: /^[0-9]*$/,message: "短信目标必须是数字", trigger: "blur"}
        ],
        callTime: [
          { required: true, message: "通时目标不能为空", trigger: "blur" },
          {pattern: /^[0-9]*$/,message: "通时目标必须是数字", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getMonday();
    this.getList();
    this.getDeptTree();
    this.getDeptAndUsers();
    this.userId = this.$store.state.user.id;

  },
  methods: {
    /** 总计 */
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }
        if(column.property != 'dept_name' && column.property != 'operation'){
          sums[index]=this.calculateSum(data,column.property);
        }else{
          sums[index]='--';
        }
      });
      return sums
    },
    calculateSum(data,name){
      let sum=0;
      data.forEach(value =>{
        sum=sum+value[name];
      });
      return sum;
    },
    /** 查询周目标管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params.queryType = this.queryType;
      listUserGoal(this.queryParams).then(response => {
        this.userGoalList = response.data.list;
        this.rightType = response.data.rightType;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        empId: null,
        orgId: null,
        visit: null,
        signed: null,
        addFriend: null,
        introduce: null,
        introduceVisit: null,
        introduceSigned: null,
        smsfollow: null,
        callTime: null,
        goalDate: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加周目标";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUserGoal(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改周目标";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUserGoal(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUserGoal(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除周目标管理编号为"' + ids + '"的数据项？').then(function () {
        return delUserGoal(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 查询部门归属下拉树结构 */
    getDeptTree() {
      var dept = { deptId: this.$store.state.user.deptid }
      childrenAlldeptTree(dept).then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 获取部门归属和人员信息 */
    getDeptAndUsers() {
      getAllDeptandUsers().then((response) => {
        this.sysUsersList = response.data.sysUsersList;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('crmsys/userGoal/export', {
        ...this.queryParams
      }, `userGoal_${new Date().getTime()}.xlsx`)
    },
    //获取本周一
    getMonday() {
      let currentDate = new Date();
      const options = { year: 'numeric', month: '2-digit', day: '2-digit' }; // 设置年、月、日的显示格式

      // 获取当前日期的星期几（0表示周日，1表示周一，以此类推）
      let dayOfWeek = currentDate.getDay();
      if (dayOfWeek == 0) {
        //周天 加一天就是周一
        currentDate.setDate(currentDate.getDate() + 1);
      } else if (dayOfWeek != 1) {
        //不是周天和周一
        // 设置date为星期一
        while (currentDate.getDay() !== 1) {
          // 如果不是星期一，则将date向后移动一天
          currentDate.setDate(currentDate.getDate() - 1);
        }
      }
      this.queryParams.goalDate = currentDate.toLocaleDateString("af");
    },
    checkGoalDate(goalDate) {
      const time = new Date(goalDate);
      const time1 = new Date();
      const time2 = time.getDate() - 1;
      return time == time1 || time == time2;
    }
  }
};
</script>

<style lang="scss" scoped>
@import '@/assets/styles/command.scss';
</style>
